// Sales Order同步到旺店通功能 - 只添加同步按钮，不覆盖现有功能

// 直接设置listview_settings
frappe.listview_settings["Sales Order"] = frappe.listview_settings["Sales Order"] || {};

// 覆盖默认状态指示器：不再根据交付日期显示“逾期”，仅展示业务状态
frappe.listview_settings["Sales Order"].get_indicator = function(doc) {
	// 统一按业务状态显示
	const status = doc.status || "";
	const colorMap = {
		"Draft": "red",
		"On Hold": "orange",
		"To Bill": "orange",
		"To Deliver": "orange",
		"Completed": "green",
		"Cancelled": "red",
		"Closed": "blue"
	};
	const color = colorMap[status] || "blue";
	// 过滤条件保持简单：基于状态精确匹配
	if (status) {
		return [__(status), color, `status,=,${status}`];
	}
	// 无状态时不返回自定义指示器，交给系统默认处理
};

// 添加onload函数
const prevOnload = frappe.listview_settings["Sales Order"].onload;
frappe.listview_settings["Sales Order"].onload = function(listview) {
    // 先调用已有的 onload（若存在），避免互相覆盖
    if (typeof prevOnload === "function") {
        try { prevOnload.call(this, listview); } catch (e) { console && console.warn && console.warn("Prev onload error:", e); }
    }

    // 避免重复初始化按钮与菜单
    if (listview._ups_buttons_initialized) {
        return;
    }

    // 保留标准筛选侧栏与菜单
    console.log("Sales Order listview onload called");
    
    // Add "Sync to WDT" menu item
    listview.page.add_menu_item(__("Sync to WDT"), function() {
        sync_sales_orders_to_wdt(listview);
    });
    
    // Cancel in WDT
    listview.page.add_menu_item(__("Cancel WDT&Shipping&Fulfillment"), function() {
        cancel_sales_orders_in_wdt(listview);
    });
    
    // 添加复制订单按钮到菜单
    listview.page.add_menu_item(__("复制订单"), function() {
        copy_sales_orders(listview);
    });

    // Shopify 同步按钮
    listview.page.add_menu_item(__("同步Shopify订单"), function() {
        open_shopify_order_sync_dialog();
    });
    
    // 仅初始化一次
    listview._ups_buttons_initialized = true;

    console.log("Sales Order buttons configured:", Object.keys(frappe.listview_settings["Sales Order"]));
};

// 添加行操作按钮
frappe.listview_settings["Sales Order"].button = {
    show: function(doc) {
        // 只对已提交的销售订单显示同步按钮
        const blocked = ["Closed", "Cancelled", "To Bill", "Completed"];
        return doc.docstatus === 1 && !blocked.includes(doc.status);
    },
    get_label: function() {
        return __("Sync to WDT");
    },
    get_description: function(doc) {
        return __("Sync Sales Order to WDT");
    },
    action: function(doc) {
        sync_single_sales_order_to_wdt(doc);
    }
};

// 添加取消订单按钮
frappe.listview_settings["Sales Order"].button_wdt_cancel = {
    show: function(doc) {
        // 只对已提交且未关闭的销售订单显示取消按钮
        return doc.docstatus === 1 && doc.status !== "Closed" && doc.status !== "Cancelled";
    },
    get_label: function() {
        return __("Cancel Order");
    },
    get_description: function(doc) {
        return __("Cancel Sales Order in WDT");
    },
    action: function(doc) {
        cancel_single_sales_order_in_wdt(doc);
    }
};

function maybe_show_low_balance_dialog(reserve_info) {
    try {
        if (!reserve_info || !reserve_info.low_balance) return;
        var balance = reserve_info.balance || 0;
        var reserved = reserve_info.reserved_today || 0;
        var msg = __("当前余额：{0}，今日预估物流费：{1}。请尽快充值，以免影响出货。", [balance, reserved]);
        var d = new frappe.ui.Dialog({
            title: __("余额不足"),
            fields: [
                {
                    fieldtype: "HTML",
                    fieldname: "body",
                    options: "<p>" + msg + "</p>"
                }
            ],
            primary_action_label: __("去充值"),
            primary_action: function () {
                d.hide();
                window.open("/app/oms_payment", "_blank");
            }
        });
        d.set_secondary_action_label(__("忽略本次"));
        d.set_secondary_action(function () {
            d.hide();
        });
        d.show();
    } catch (e) {
        console && console.warn && console.warn("low balance dialog error", e);
    }
}

// 同步单个销售订单到旺店通
function sync_single_sales_order_to_wdt(doc) {
    // 调试信息
    console.log("sync_single_sales_order_to_wdt called with doc:", doc);
    
    // 检查doc和name是否存在
    if (!doc) {
        frappe.msgprint(__("Error: Sales Order not found"));
        return;
    }
    
    // 获取销售订单名称
    let salesOrderName = doc.name;
    
    if (!salesOrderName) {
        frappe.msgprint(__("Error: Sales Order name missing"));
        console.log("Available doc fields:", Object.keys(doc));
        return;
    }
    
    // 检查销售订单状态
    if (doc.docstatus !== 1) {
        frappe.msgprint(__("Only submitted Sales Orders can be synced to WDT"));
        return;
    }
    
    if (doc.status === "Closed") {
        frappe.msgprint(__("Closed Sales Orders cannot be synced to WDT"));
        return;
    }
    
    frappe.confirm(
        __("Sync Sales Order '{0}' to WDT?", [salesOrderName]),
        function() {
            frappe.call({
                method: "upsystem.upsystem.api.sync_sales_order_to_wdt",
                args: {
                    sales_order_name: salesOrderName
                },
                callback: function(r) {
                    if (r.message && r.message.success) {
                        frappe.show_alert({
                            message: __("Sales Order synced to WDT"),
                            indicator: "green"
                        });
                        if (r.message.reserve_info) {
                            maybe_show_low_balance_dialog(r.message.reserve_info);
                        }
                    } else {
                        let errorMsg = r.message.message || "Unknown error";
                        frappe.msgprint({
                            title: __("Sync Failed"),
                            message: __("Sales Order sync failed: {0}", [errorMsg]),
                            indicator: "red"
                        });
                    }
                },
                error: function(err) {
                    frappe.show_alert({
                        message: __("Sync failed: {0}", [err.message || "Network error"]),
                        indicator: "red"
                    });
                }
            });
        }
    );
}

function open_shopify_order_sync_dialog() {
    const dialog = new frappe.ui.Dialog({
        title: __("同步 Shopify 订单"),
        fields: [
            {
                fieldtype: "Link",
                label: __("Shopify 店铺"),
                fieldname: "usershop",
                options: "usershop",
                reqd: 1,
            },
            {
                fieldtype: "Int",
                label: __("批次大小"),
                fieldname: "batch_size",
                default: 50,
            },
            {
                fieldtype: "Int",
                label: __("最大分页数"),
                fieldname: "max_pages",
                default: 1,
            },
            {
                fieldtype: "Data",
                label: __("增量开始时间 (ISO8601)"),
                fieldname: "since",
                description: __("例如 2025-01-01T00:00:00Z，可留空"),
            },
        ],
        primary_action_label: __("开始同步"),
        primary_action(values) {
            dialog.hide();
            run_shopify_order_sync(values);
        },
    });

    dialog.show();
}

function run_shopify_order_sync(values) {
    const shopName = values.usershop;
    if (!shopName) {
        frappe.msgprint(__("请选择 Shopify 店铺"));
        return;
    }

    const payload = {
        shop_name: shopName,
        batch_size: values.batch_size || 50,
        max_pages: values.max_pages || 1,
    };

    if (values.since) {
        payload.since = values.since;
    }

    frappe.db
        .get_value("usershop", shopName, ["company"])
        .then((r) => {
            if (r && r.message && r.message.company) {
                payload.company = r.message.company;
            }

            frappe.call({
                method: "upsystem.upsystem.api_shop.sync_shopify_orders",
                args: payload,
                freeze: true,
                freeze_message: __("正在同步Shopify订单…"),
                callback(res) {
                    if (res.exc) {
                        return;
                    }

                    const msg = res.message || {};
                    frappe.msgprint({
                        title: __("同步完成"),
                        message: __(
                            "同步成功：获取 {0} 条，新建 {1} 条，更新 {2} 条",
                            [msg.fetched || 0, msg.created || 0, msg.updated || 0]
                        ),
                        indicator: "green",
                    });
                },
                error(err) {
                    frappe.msgprint({
                        title: __("同步失败"),
                        message: err?.message || __("调用接口失败，请稍后重试。"),
                        indicator: "red",
                    });
                },
            });
        });
}

// 取消单个销售订单在旺店通中的对应单据
function cancel_single_sales_order_in_wdt(doc) {
    // 调试信息
    console.log("cancel_single_sales_order_in_wdt called with doc:", doc);
    
    // 检查doc和name是否存在
    if (!doc) {
        frappe.msgprint(__("错误：未找到销售订单信息"));
        return;
    }
    
    // 获取销售订单名称
    let salesOrderName = doc.name;
    
    if (!salesOrderName) {
        frappe.msgprint(__("错误：销售订单名称不存在"));
        console.log("Available doc fields:", Object.keys(doc));
        return;
    }
    
    // 检查销售订单状态
    if (doc.docstatus !== 1) {
        frappe.msgprint(__("只有已提交的销售订单才能取消"));
        return;
    }
    
    if (doc.status === "Closed") {
        frappe.msgprint(__("已关闭的销售订单不能取消"));
        return;
    }
    
    if (doc.status === "Cancelled") {
        frappe.msgprint(__("已取消的销售订单不能重复取消"));
        return;
    }
    
    // 显示取消原因输入对话框
    let d = new frappe.ui.Dialog({
        title: __("取消销售订单"),
        fields: [
            {
                "fieldtype": "Data",
                "fieldname": "cancel_reason",
                "label": __("取消原因"),
                "reqd": 1,
                "placeholder": "请输入取消原因..."
            }
        ],
        primary_action_label: __("确认取消"),
        primary_action: function(values) {
            d.hide();
            
            // 获取当前用户和时间信息
            let currentUser = frappe.user.name;
            let currentDateTime = frappe.datetime.now_datetime();
            
            // 组合完整的取消原因
            let fullCancelReason = `${values.cancel_reason} | 取消人: ${currentUser} | 取消时间: ${currentDateTime}`;
            
            frappe.call({
                method: "upsystem.upsystem.api.cancel_sales_order_in_wdt",
                args: {
                    sales_order_name: salesOrderName,
                    cancel_reason: fullCancelReason
                },
                callback: function(r) {
                    show_cancel_result_dialog(salesOrderName, values.cancel_reason, r.message);
                },
                error: function(err) {
                    frappe.show_alert({
                        message: __("取消失败: {0}", [err.message || "网络错误"]),
                        indicator: "red"
                    });
                }
            });
        }
    });
    
    d.show();
}

// 显示取消订单结果弹框
function show_cancel_result_dialog(salesOrderName, cancelReason, result) {
    let message = "";
    
    // 构建更友好的显示信息
    if (result && result.success) {
        message = __("订单取消成功！");
        
        // 显示云途订单撤销信息
        if (result.data && result.data.yt_canceled) {
            if (result.data.yt_cancel_result && result.data.yt_cancel_result.success) {
                message += __("\n云途订单 {0} 已成功撤销", [result.data.yt_waybill_number]);
            } else {
                message += __("\n云途订单 {0} 撤销失败", [result.data.yt_waybill_number]);
            }
        }
    } else {
        message = __("订单取消失败: {0}", [result.message || "未知错误"]);
        
        // 显示云途订单撤销信息
        if (result.yt_canceled) {
            if (result.yt_cancel_result && result.yt_cancel_result.success) {
                message += __("\n云途订单 {0} 已成功撤销", [result.yt_waybill_number]);
            } else {
                message += __("\n云途订单 {0} 撤销失败", [result.yt_waybill_number]);
            }
        }
    }
    
    let d = new frappe.ui.Dialog({
        title: __("取消订单结果 - {0}", [salesOrderName]),
        fields: [
            {
                "fieldtype": "Small Text",
                "fieldname": "result_message",
                "label": __("结果信息"),
                "default": message,
                "read_only": 1
            },
            {
                "fieldtype": "Small Text",
                "fieldname": "result_json",
                "label": __("详细返回结果"),
                "default": JSON.stringify(result, null, 2),
                "read_only": 1
            }
        ],
        size: "large"
    });
    
    d.show();
}

// 批量同步销售订单到旺店通
function sync_sales_orders_to_wdt(listview) {
    // 调试信息
    console.log("sync_sales_orders_to_wdt called with listview:", listview);
    
    // 获取选中的销售订单 - 使用正确的方法
    let selected_orders = [];
    
    // 方法1：尝试使用get_checked_items()
    if (typeof listview.get_checked_items === 'function') {
        selected_orders = listview.get_checked_items();
        console.log("get_checked_items()返回:", selected_orders);
    }
    
    // 方法2：如果上面方法返回的不是数组或为空，尝试其他方法
    if (!Array.isArray(selected_orders) || selected_orders.length === 0) {
        console.log("尝试其他方法获取选中销售订单");
        
        // 从DOM获取选中的行
        let checked_rows = listview.wrapper.find('input[type="checkbox"]:checked');
        console.log("找到选中的复选框数量:", checked_rows.length);
        
        checked_rows.each(function() {
            let checkbox = $(this);
            let row = checkbox.closest('tr, .list-row');
            
            // 获取销售订单名称 - 尝试多种方式
            let sales_order_name = row.find('[data-fieldname="name"]').text().trim() ||
                                 row.find('.list-row-col[data-fieldname="name"]').text().trim() ||
                                 row.attr('data-name') ||
                                 row.find('a[data-name]').attr('data-name') ||
                                 row.find('.list-row-col:first').text().trim();
            
            if (sales_order_name && sales_order_name.length > 1) { // 确保不是单个字符
                selected_orders.push({name: sales_order_name});
                console.log("找到销售订单名称:", sales_order_name);
            }
        });
    }
    
    console.log("最终选中的销售订单:", selected_orders);
    
    if (selected_orders.length === 0) {
        frappe.msgprint(__("请先选择要同步的销售订单"));
        return;
    }

    // 读取这些订单的当前状态，屏蔽“待收货”等不允许状态
    let names_to_check = [];
    selected_orders.forEach(order => {
        const name = order.name || order;
        if (name && name.length > 1) names_to_check.push(name);
    });

    frappe.db.get_list('Sales Order', {
        filters: [['name', 'in', names_to_check]],
        fields: ['name', 'status', 'docstatus']
    }).then(records => {
        const blocked = [];
        const allowed = [];
        records.forEach(r => {
            const notSubmitted = r.docstatus !== 1;
            const disallowedStatus = ["Closed", "Cancelled", "To Bill", "Completed"].includes(r.status);
            if (notSubmitted || disallowedStatus) {
                blocked.push(r);
            } else {
                allowed.push(r.name);
            }
        });

        if (allowed.length === 0) {
            frappe.msgprint(__("所选订单状态不允许同步（已出库/关闭/取消或未提交）。"));
            return;
        }

        if (blocked.length > 0) {
            const blockedInfo = blocked.map(b => `${b.name} (${b.status || 'Draft'})`).join(', ');
            frappe.show_alert({ message: __("以下订单被跳过：{0}", [blockedInfo]), indicator: "orange" });
        }

        frappe.confirm(
            __("确定要将选中的 {0} 个销售订单同步到旺店通吗？", [allowed.length]),
            function() {
                frappe.call({
                    method: "upsystem.upsystem.api.batch_sync_sales_orders_to_wdt",
                    args: { sales_order_names: allowed },
                    callback: function(r) {
                        if (r.message && r.message.success) {
                            let success_count = r.message.data.success_count || 0;
                            let fail_count = r.message.data.fail_count || 0;
                            let results = r.message.data.results || [];

                            if (fail_count === 0) {
                                frappe.show_alert({
                                    message: __("所有销售订单同步成功！共 {0} 个", [success_count]),
                                    indicator: "green"
                                });
                            } else {
                                let fail_orders = results.filter(x => !x.success).map(x => x.sales_order_name).join(', ');
                                frappe.msgprint({
                                    title: __("同步完成"),
                                    message: __("成功: {0} 个，失败: {1} 个<br/>失败订单: {2}", [success_count, fail_count, fail_orders]),
                                    indicator: "orange"
                                });
                            }
                            listview.refresh();
                        } else {
                            frappe.msgprint({
                                title: __("同步失败"),
                                message: __("批量同步失败: {0}", [r.message.message || "未知错误"]),
                                indicator: "red"
                            });
                        }
                    },
                    error: function(err) {
                        frappe.show_alert({
                            message: __("批量同步失败: {0}", [err.message || "网络错误"]),
                            indicator: "red"
                        });
                    }
                });
            }
        );
    });
}

// 批量取消销售订单在旺店通中的对应单据
function cancel_sales_orders_in_wdt(listview) {
    console.log("cancel_sales_orders_in_wdt called with listview:", listview);
    
    // 获取选中的销售订单
    let selected_orders = [];
    
    if (typeof listview.get_checked_items === 'function') {
        selected_orders = listview.get_checked_items();
    }
    
    if (!Array.isArray(selected_orders) || selected_orders.length === 0) {
        let checked_rows = listview.wrapper ? listview.wrapper.find('input[type="checkbox"]:checked') : $('input[type="checkbox"]:checked');
        
        checked_rows.each(function() {
            let checkbox = $(this);
            let row = checkbox.closest('tr, .list-row');
            
            let sales_order_name = row.find('[data-fieldname="name"]').text().trim() ||
                                 row.find('.list-row-col[data-fieldname="name"]').text().trim() ||
                                 row.attr('data-name') ||
                                 row.find('a[data-name]').attr('data-name') ||
                                 row.find('.list-row-col:first').text().trim();
            
            if (sales_order_name && sales_order_name.length > 1) {
                selected_orders.push({name: sales_order_name});
            }
        });
    }
    
    if (selected_orders.length === 0) {
        frappe.msgprint(__("请先选择要取消的销售订单"));
        return;
    }
    
    // 仅允许 To Deliver 状态执行取消；其它状态直接拦截
    const names = selected_orders.map(o => o.name || o).filter(n => n && n.length > 1);
    frappe.db.get_list('Sales Order', {
        filters: [['name', 'in', names]],
        fields: ['name', 'status', 'docstatus']
    }).then(records => {
        const allowed = records.filter(r => r.docstatus === 1 && r.status === "To Deliver").map(r => r.name);
        const blocked = records.filter(r => r.docstatus !== 1 || r.status !== "To Deliver");

        if (allowed.length === 0) {
            frappe.msgprint(__("仅“待发货”(To Deliver) 状态允许执行取消，所选均不符合。"));
            return;
        }
        if (blocked.length > 0) {
            const blockedInfo = blocked.map(b => `${b.name} (${b.status || 'Draft'})`).join(', ');
            frappe.show_alert({ message: __("以下订单已被跳过：{0}", [blockedInfo]), indicator: "orange" });
        }

        const wrapped = allowed.map(n => ({ name: n }));
        if (wrapped.length > 5) {
            frappe.confirm(__("您选择了 {0} 个销售订单，确定要取消吗？", [wrapped.length]), function() {
                cancel_multiple_sales_orders_in_wdt(wrapped);
            });
        } else {
            cancel_multiple_sales_orders_in_wdt(wrapped);
        }
    });
}

// 取消多个销售订单
function cancel_multiple_sales_orders_in_wdt(selected_orders) {
    let sales_order_names = selected_orders.map(order => {
        let name = order.name || order;
        return name;
    }).filter(name => name && name.length > 1);
    
    // 显示批量取消原因输入对话框
    let d = new frappe.ui.Dialog({
        title: __("批量取消销售订单"),
        fields: [
            {
                "fieldtype": "Data",
                "fieldname": "cancel_reason",
                "label": __("取消原因"),
                "reqd": 1,
                "placeholder": "请输入批量取消原因..."
            }
        ],
        primary_action_label: __("确认批量取消"),
        primary_action: function(values) {
            d.hide();
            
            // 获取当前用户和时间信息
            let currentUser = frappe.user.name;
            let currentDateTime = frappe.datetime.now_datetime();
            
            // 组合完整的取消原因
            let fullCancelReason = `${values.cancel_reason} | 取消人: ${currentUser} | 取消时间: ${currentDateTime}`;
            
            frappe.show_alert({
                message: __("正在取消 {0} 个销售订单...", [sales_order_names.length]),
                indicator: "blue"
            });
            
            let all_cancel_data = [];
            let completed_count = 0;
            
            sales_order_names.forEach(function(sales_order_name, index) {
                frappe.call({
                    method: "upsystem.upsystem.api.cancel_sales_order_in_wdt",
                    args: {
                        sales_order_name: sales_order_name,
                        cancel_reason: fullCancelReason
                    },
                    callback: function(r) {
                        completed_count++;
                        
                        if (r.message && r.message.success) {
                            all_cancel_data.push({
                                sales_order: sales_order_name,
                                success: true,
                                data: r.message.data
                            });
                        } else {
                            let errorMsg = r.message.message || "Cancel failed";
                            let wdtCode = r.message.wdt_code || "";
                            let wdtFlag = r.message.wdt_flag || "";
                            let wdtMessage = r.message.wdt_message || "";
                            
                            let detailedError = errorMsg;
                            if (wdtCode || wdtFlag || wdtMessage) {
                                // Use generic WMS label, avoid provider-specific names
                                detailedError += ` (WMS: ${wdtCode || wdtFlag || wdtMessage})`;
                            }
                            
                            all_cancel_data.push({
                                sales_order: sales_order_name,
                                success: false,
                                error: detailedError,
                                wdt_code: wdtCode,
                                wdt_flag: wdtFlag,
                                wdt_message: wdtMessage
                            });
                        }
                        
                        if (completed_count === sales_order_names.length) {
                            show_batch_cancel_result_dialog({
                                success: true,
                                data: {
                                    success_count: all_cancel_data.filter(item => item.success).length,
                                    fail_count: all_cancel_data.filter(item => !item.success).length,
                                    results: all_cancel_data
                                }
                            });
                        }
                    },
            error: function(err) {
                        completed_count++;
                        all_cancel_data.push({
                            sales_order: sales_order_name,
                            success: false,
                    error: err.message || "Network error"
                        });
                        
                        if (completed_count === sales_order_names.length) {
                            show_batch_cancel_result_dialog({
                                success: true,
                                data: {
                                    success_count: all_cancel_data.filter(item => item.success).length,
                                    fail_count: all_cancel_data.filter(item => !item.success).length,
                                    results: all_cancel_data
                                }
                            });
                        }
                    }
                });
            });
        }
    });
    
    d.show();
}

// 显示批量取消订单结果弹框
function show_batch_cancel_result_dialog(result) {
    let d = new frappe.ui.Dialog({
        title: __("Batch Cancel Result"),
        fields: [
            {
                "fieldtype": "Small Text",
                "fieldname": "result_json",
                "label": __("Response Data"),
                "default": JSON.stringify(result, null, 2),
                "read_only": 1
            }
        ],
        size: "large"
    });
    
    d.show();
}

// 复制单个销售订单
function copy_single_sales_order(doc) {
    if (!doc) {
        frappe.msgprint(__("错误：未找到销售订单信息"));
        return;
    }
    
    let salesOrderName = doc.name;
    if (!salesOrderName) {
        frappe.msgprint(__("错误：销售订单名称不存在"));
        return;
    }
    
    // 显示复制订单对话框
    let d = new frappe.ui.Dialog({
        title: __("复制销售订单"),
        fields: [
            {
                "fieldtype": "Date",
                "fieldname": "new_delivery_date",
                "label": __("新交付日期"),
                "default": frappe.datetime.add_days(frappe.datetime.get_today(), 7)
            }
        ],
        primary_action_label: __("确认复制"),
        primary_action: function(values) {
            d.hide();
            
            frappe.call({
                method: "upsystem.upsystem.api.copy_sales_order",
                args: {
                    sales_order_name: salesOrderName,
                    new_delivery_date: values.new_delivery_date || null
                },
                callback: function(r) {
                    if (r.message && r.message.success) {
                        frappe.show_alert({
                            message: __("订单复制成功！新订单：{0}", [r.message.data.new_order_name]),
                            indicator: "green"
                        });
                        
                        // 打开新订单
                        frappe.set_route("Form", "Sales Order", r.message.data.new_order_name);
                    } else {
                        frappe.show_alert({
                            message: __("复制失败: {0}", [r.message.message || "未知错误"]),
                            indicator: "red"
                        });
                    }
                },
                error: function(err) {
                    frappe.show_alert({
                        message: __("复制失败: {0}", [err.message || "网络错误"]),
                        indicator: "red"
                    });
                }
            });
        }
    });
    
    d.show();
}

// 批量复制销售订单
function copy_sales_orders(listview) {
    // 获取选中的销售订单
    let selected_orders = [];
    
    if (typeof listview.get_checked_items === 'function') {
        selected_orders = listview.get_checked_items();
    } else if (listview.selected_items) {
        selected_orders = listview.selected_items;
    }
    
    if (selected_orders.length === 0) {
        frappe.msgprint(__("请先选择要复制的销售订单"));
        return;
    }
    
    if (selected_orders.length > 1) {
        frappe.msgprint(__("请一次只选择一个订单进行复制"));
        return;
    }
    
    // 复制选中的订单
    copy_single_sales_order(selected_orders[0]);
}